package com.xianyun.rpc.serializer;

import com.xianyun.rpc.constant.SerializerKeys;
import com.xianyun.rpc.serializer.impl.HessianSerializer;
import com.xianyun.rpc.serializer.impl.JdkSerializer;
import com.xianyun.rpc.serializer.impl.JsonSerializer;
import com.xianyun.rpc.serializer.impl.KryoSerializer;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * 工厂模式+单例模式维护序列化器（序列化器不需要重复创建）
 * @author xianYun
 * @version 1.0
 **/
@Slf4j
public class SerializerFactory {
    private static final Map<String,Serializer> serializerMap = new HashMap<>()
    {{
        put(SerializerKeys.JDK,new JdkSerializer());
        put(SerializerKeys.JSON,new JsonSerializer());
        put(SerializerKeys.KRYO,new KryoSerializer());
        put(SerializerKeys.HESSIAN,new HessianSerializer());
    }};

    private static final String DEFAULT_SERIALIZER = SerializerKeys.JDK;

    /**
     * 获取序列化器的实例
     * @param serializerName 序列化器的名字。
     * @return
     */
    public static Serializer getSerializer(String serializerName) {
        Serializer serializer = serializerMap.get(serializerName);
        //如果没有用户指定的序列化器，则使用默认的序列化器
        if (serializer == null){
            log.warn("THE SPECIFIED SERIALIZER WAS NOT FOUND");
            return serializerMap.get(DEFAULT_SERIALIZER);
        }
        return serializer;
    }
}
